//
//  String+Size.swift
//  MT
//
//  Created by zhang qiang on 2018/11/21.
//  Copyright © 2018年 张强. All rights reserved.
//

import Foundation
import UIKit

public extension String{
    
    func height(font: UIFont, maxWidth: CGFloat) -> CGFloat{
        let rect = self.boundingRect(with: CGSize.init(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin.union(NSStringDrawingOptions.usesFontLeading), attributes: [NSAttributedString.Key.font : font], context: nil)
        return rect.size.height
    }
    
    
    func width(font: UIFont, maxHeight: CGFloat) -> CGFloat{
        let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: maxHeight), options: NSStringDrawingOptions.usesLineFragmentOrigin.union(NSStringDrawingOptions.usesFontLeading), attributes: [NSAttributedString.Key.font : font], context: nil)
        return rect.size.width
    }
    
    func get(rectWithFont font: UIFont, size: CGSize = .zero) -> CGRect {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        return (self as NSString).boundingRect(with: size, options: option, attributes: attributes, context: nil)
    }
    
    func py() -> String {
        let mutableString = NSMutableString(string: self)
        //把汉字转为拼音
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        //去掉拼音的音标
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let py = String(mutableString)
        return py
    }
    
    func firstCharacter() -> String {
        let firstCharacter = String(describing: self.first!)
        if firstCharacter.isLetterOrNum() {
            return firstCharacter.uppercased()
        }
        let py = String(describing: firstCharacter.py().first!)
        return py.uppercased()
    }
    
    func isLetterOrNum() -> Bool {
        if let value = UnicodeScalar(self)?.value {
            if value >= 65 && value <= 90 {
                return true
            }
        }
        return false
    }
    
}
